/**
 * @class   GardenerProgram
 * @brief   Interface for 
 *
 ****************************************************************************
 * @version $Id: GardenerProgram.h 2891 2010-08-12 01:58:59Z alex $
 * @author Alessandro Polo
 * @date   Released on 2009-06-04
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_SERVICES_GardenerProgram_H__
 #define __WOSH_SERVICES_GardenerProgram_H__

 #include <woshDefs.h>
 #include <core/Object.h>
 #include <core/LogContext.h>
 #include <core/Message.h>
 #include <core/Thread.h>
 #include <core/Containers.h>
 #include <framework/xtended/WeatherInfo.h>
 #include "IGardenerProgramListener.h"


#ifdef WOSH_PERSISTENCE_QT
 #include <framework/persistence/qt/EncoderProtocolXmlQt.h>
#endif // WOSH_PERSISTENCE_QT


namespace wosh {
 template <class T> class DataFieldCollector;
 namespace services {


class GardenerProgramTask : public IReflection
 {
	WOSH_CLASSNAME(wosh::services::GardenerProgramTask)
	WOSH_CLASS_ABSTRACT(false)

	public:
		GardenerProgramTask();
		virtual ~GardenerProgramTask();

	public:
		Message* createZoneMessage( short action ) const;

		long calculateTaskTime();

	public:
		inline const URI& getZone() const				{ return this->targetGardenZone; }
		inline URI& getZone()							{ return this->targetGardenZone; }

		inline long getLimitTimeMin() const				{ return this->time_min; }
		inline long getLimitTimeMax() const				{ return this->time_max; }
		inline long getLimitWaterLevel() const			{ return this->water_level; }
		inline long getLimitTimePeriod() const			{ return this->time_period; }

		inline long getTaskTime() const					{ return this->current_TaskTime; }

	public:
		inline void setLimitTimeMin( long value )		{ this->time_min = value; }
		inline void setLimitTimeMax( long value )		{ this->time_max = value; }
		inline void setLimitWaterLevel( long value )	{ this->water_level = value; }
		inline void setLimitTimePeriod( long value )	{ this->time_period = value; }

		void clearLimits();

	public:
		URI targetGardenZone;

	protected: // limits
		long time_min;				///< minimum time in seconds foreach session. 0=disabled
		long time_max;				///< maximum time in seconds foreach session. 0=disabled
		long water_level;			///< millimeters per period (= 1 liter / m^2)
		long time_period;			///< period in seconds between each session

		long current_TaskTime;

	public: // stats
		mutable long stats_lastTaskTime;
}; // class def


typedef ListT<GardenerProgramTask*> tGardenerProgramTaskList;


class GardenerProgram :	protected ThreadImpl,
						public Object
 {
	WOSH_CLASSNAME(wosh::services::GardenerProgram)
	WOSH_CLASS_ABSTRACT(false)

	public:
		enum PROGRAM_TYPE {
			TYPE_UNKNOWN	= 0x00,	///< unkown, default during initialization
			TYPE_STATIC		= 0x01,	///< defined by the system, read-only, no self reconfiguration
			TYPE_USER		= 0x02,	///< defined by user(s), read-only, no self reconfiguration
			TYPE_AUTO		= 0x04	///< self reconfiguration enabled
		 };

	public:
		GardenerProgram();
		virtual ~GardenerProgram() { }

	public:
		void evaluateWeatherUpdate( const wosh::xtended::WeatherInfo* updated_info, double similarity = -1.0 );

	public:
		WRESULT start();
		WRESULT stop();
		WRESULT pause( unsigned long seconds );

		WRESULT startTask( GardenerProgramTask* task );
		WRESULT stopTask( GardenerProgramTask* task );
		WRESULT waitTask( GardenerProgramTask* task, bool* semaphore );

	public:
		inline int64 getID() const							{ return this->uid; }
		inline bool isEnabled() const						{ return this->enabled; }
		inline bool isActive() const						{ return isThreadRunning(); }
		inline long getPriority() const						{ return this->priority; }
		inline PROGRAM_TYPE getProgramType() const			{ return this->type; }

		inline int64 getNextStartTime() const				{ return this->next_interrupt; }
		unsigned long getProjectedProgramLength() const;

		IGardenerProgramListener* getListener()				{ return this->listener; }

		const tGardenerProgramTaskList& getTasks() const	{ return this->tasks; }
		tGardenerProgramTaskList& getTasks()				{ return this->tasks; }

		static DataFieldCollector<GardenerProgram>* getDataFields();

	public:
		void setName( const std::string& value );
		inline void setEnabled( bool value )				{ this->enabled = value; }
		inline void setPriority( long value )				{ this->priority = value; }
		inline void setProgramType( PROGRAM_TYPE ptr )		{ this->type = ptr; }

		WRESULT setStartSettings( int hour, int min, bool end_time = false, const std::string& modifier_event = "" );

		void setListener( IGardenerProgramListener* ptr )	{ this->listener = ptr; }

		void setNextStartTime( int64 time );
	//	int64 calculateNextStartTime();

	protected:
		virtual bool initializingThread();
		virtual void runThread();

	protected:
		WRESULT selectNextTask_();

	protected:
		int64 uid;							///<
		LogContext Log;						///<
		bool enabled;						///<
		PROGRAM_TYPE type;					///<
		long priority;						///<

		int64 next_interrupt;
		std::string modifier_event_key;
		bool def_end_time;

		tGardenerProgramTaskList tasks;		///<
		GardenerProgramTask* cTask;			///<

		IGardenerProgramListener* listener;

}; // class def


 }; // namespace services


#ifdef WOSH_PERSISTENCE_QT

 namespace persistence {
  namespace qt {

WOSH_ENCODER_XML_Qt_CLASS(EncoderXml_Qt_Services_GardenerProgram, wosh::services::GardenerProgram)
WOSH_ENCODER_XML_Qt_CLASS(EncoderXml_Qt_Services_GardenerProgramTask, wosh::services::GardenerProgramTask)

  }; // namespace qt
 }; // namespace persistence

#endif // WOSH_PERSISTENCE_QT


}; // namespace wosh

#endif //__WOSH_SERVICES_GardenerProgram_H__
